package com.supply.dl.widget.span;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

/**
 * <p></p>
 * <p>com.forum.app.widget</p>
 * <p>2014/12/19 15:15</p>
 * @author yangting
 * @version CmgeForum 1.0.0
 */
public class VerticalImageSpan extends ImageSpan
{
	private Drawable mDrawable;

	public VerticalImageSpan(Drawable drawable)
	{
		super(drawable);
		this.mDrawable = drawable;
	}

	public void setDrawable(Drawable mDrawable)
	{
		this.mDrawable = mDrawable;
	}

	@Override
	public Drawable getDrawable()
	{
		return mDrawable;
	}

	public int getSize(Paint paint, CharSequence text, int start, int end,
			Paint.FontMetricsInt fontMetricsInt)
	{
		Drawable drawable = mDrawable;
		if (drawable == null)
			return 0;
		Rect rect = drawable.getBounds();
		if (fontMetricsInt != null)
		{
			Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
			int fontHeight = fmPaint.bottom - fmPaint.top;
			int drHeight = rect.bottom - rect.top;

			int top = drHeight / 2 - fontHeight / 4;
			int bottom = drHeight / 2 + fontHeight / 4;

			fontMetricsInt.ascent = -bottom;
			fontMetricsInt.top = -bottom;
			fontMetricsInt.bottom = top;
			fontMetricsInt.descent = top;
		}
		return rect.right;
	}

	@Override
	public void draw(Canvas canvas, CharSequence text, int start, int end,
			float x, int top, int y, int bottom, Paint paint)
	{
		Drawable drawable = mDrawable;
		if (drawable == null)
			return;
		canvas.save();
		int transY;
		transY = ((bottom - top) - drawable.getBounds().bottom) / 2 + top;
		canvas.translate(x, transY);
		drawable.draw(canvas);
		canvas.restore();
	}
}
